import 'package:flutter/cupertino.dart';
import 'package:lib_database/objectbox.dart';
import 'package:lib_database/sp.dart';
import 'package:lib_database/src/bean.dart';
import 'package:lib_network/lib_network.dart';
import 'package:lib_util/lib_util.dart';

import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/network/http_api.dart';
import '../model/dapp_hot_model.dart';
import '../model/dapp_model.dart';

enum LoadPageState { none, loading, error, empty }

class DAppProvider extends ChangeNotifier {
  List<DappBannerModel> banners = [];
  int bannersDuration = 3000;

  late List<DAppBean> favoriteDAppList = [];

  double scrollNum = 0;

  bool isLoading = true;
  bool isBannerLoading = true;
  late List<BookMarkListModel> hotList = [];
  late List<String> dappsNameList = [];
  late List<BookMarkListModel> dappsList = [];

  // DAppIndexBean? dAppIndex;
  // LoadPageState dAppIndexState = LoadPageState.none;
  //String uid
  DAppProvider() {

  }

  initData(String uid){
    _getCacheData();
    refreshFavoriteDAppList(uid);
    reloadData();
  }

  Future<void> reloadData() async {
    await _loadDappBannerData();
    // final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
    // refreshFavoriteDAppList(userId);//本地实时刷新，所以不需要重新获取
    await _loadDAppHot();
  }

  _getCacheData() {
    Map<String, dynamic> bannerData = SP().getDappBannerList();
    if (!bannerData.isEmpty) {
      isBannerLoading = false;
      _calculateBanners(bannerData);
    }

    Map<String, dynamic> hotData = SP().getDappHotData();
    if (!hotData.isEmpty) {
      isLoading = false;
      var model = DAppWalletHotModel.fromJson(hotData);
      final BookMarkListModel hotDataList =
          model.bookmarkList!.firstWhere((element) {
        return element.bookmark.name == 'hot';
      });
      var resultList = hotDataList.children?[0].children?.toList() ?? [];
      hotList = resultList;

      final BookMarkListModel dappDataList =
          model.bookmarkList!.firstWhere((element) {
        return element.bookmark.name == 'dapps';
      });
      dappsList = dappDataList.children ?? [];
      dappsNameList = [];
      dappsList.forEach((element) {
        dappsNameList.add(element.bookmark.name);
      });
    }
    notifyListeners();
  }

  Future<void> _walletEscape(wallet_id) async {
    var params = {"wallet_id": wallet_id};
    var resp = await HttpManager().post(API.walletEscape, params);

    if (resp?.code == HttpConfig().successCode) {
      notifyListeners();
    }

    notifyListeners();
  }

  Future<void> _loadDappBannerData() async {
    try{
      var params = {"bannerId": 1};
      var resp = await HttpManager().get(API.walletDAppBanners, params);

      if (resp?.code == HttpConfig().successCode) {
        SP().setDappBannerList(resp!.data);
        _calculateBanners(resp.data);
        notifyListeners();
      }

      isBannerLoading = false;
      notifyListeners();
    }catch(e){
      print('_loadDappBannerData  $e');
    }
  }

  //处理banner数据
  void _calculateBanners(Map<String, dynamic> json) {
    var model = DappWalletBannerModel.fromJson(json);
    DappBannerTagModel? result = model.bannerTagList!.firstWhere(
      (element) => element.showName == 'dappindex1',
      orElse: () => DappBannerTagModel(
          id: -10086, appId: 10086, showName: 'dappindex1', positions: []),
    );
    banners =
        (result.positions!.length > 0 ? result.positions![0].banners : [])!;
    bannersDuration = (result.positions!.length > 0
        ? (result.positions![0].duration * 1000).toInt()
        : 3000);
  }

  listenScrollSetNum(double value) {
    scrollNum = value;
    notifyListeners();
  }

  setIsBannerLoading(bool isLoading) {
    isBannerLoading = isLoading;
    notifyListeners();
  }

  refreshFavoriteDAppList(String uid) {
    favoriteDAppList = ObjectBox().favoriteDAppModel.getAllFavoriteDApp(uid);
  }

  isFavoriteDAppExisted(DAppBean dApp) {
    return ObjectBox().favoriteDAppModel.isFavorite(dApp);
  }

  addOrRemoveFavoriteDApp(DAppBean dApp) {
    if (ObjectBox().favoriteDAppModel.isFavorite(dApp)) {
      removeFavorite(dApp);
    } else {
      addFavorite(dApp);
    }
  }

  addFavorite(DAppBean dApp) {
    if (ObjectBox().favoriteDAppModel.addFavoriteDApp(dApp)) {
      refreshFavoriteDAppList(dApp.uid!);
      notifyListeners();
    }
  }

  removeFavorite(DAppBean dApp) {
    if (ObjectBox().favoriteDAppModel.removeFavoriteDApp(dApp)) {
      refreshFavoriteDAppList(dApp.uid!);
      notifyListeners();
    }
  }

  Future<void> _loadDAppHot() async {
    try {
      var params = {"type": 0, "id": 0};
      var resp = await HttpManager().post(API.walletDAppHot, params);
      if (resp?.code == HttpConfig().successCode) {
        SP().setDappHotData(resp!.data);
        var model = DAppWalletHotModel.fromJson(resp.data);
        final BookMarkListModel hotDataList =
            model.bookmarkList!.firstWhere((element) {
          return element.bookmark.name == 'hot';
        });
        var resultList = hotDataList.children?[0].children?.toList() ?? [];
        hotList = resultList;

        final BookMarkListModel dappDataList =
            model.bookmarkList!.firstWhere((element) {
          return element.bookmark.name == 'dapps';
        });

        dappsList = dappDataList.children ?? [];
        dappsNameList = [];
        dappsList.forEach((element) {
          dappsNameList.add(element.bookmark.name);
        });

        // notifyListeners();
      }
    } catch (e) {
      Log.logger.e(e);
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }
}
